package com.bee.beemanage.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bee.beemanage.api.entity.SysUserLogin;
import com.bee.beemanage.api.mapper.SysUserLoginMapper;
import com.bee.beemanage.api.service.SysUserLoginService;
import com.bee.beemanage.system.common.utils.redis.RedisUtils;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultTool;
import com.bee.beemanage.system.common.utils.transaction.TransUtils;
import com.bee.beemanage.system.common.utils.transaction.Transaction;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户登录表 服务实现类
 * </p>
 *
 * @author 陈国松
 * @since 2023-02-24
 */
@Service
public class SysUserLoginServiceImpl extends ServiceImpl<SysUserLoginMapper, SysUserLogin> implements SysUserLoginService {

    @Resource
    RedisUtils redisUtils;
    @Resource
    SysUserLoginMapper sysUserLoginMapper;

    /**
     * 强制下线
     *
     * @param id 用户登录表id
     * @return 返回
     */
    @Override
    public Result forceOffline(String id) {
        Result result = ResultTool.success();
        //根据id查询用户登录信息
        SysUserLogin sysUserLogin = sysUserLoginMapper.selectById(id);
        redisUtils.del("LoginUsers:" + sysUserLogin.getToken());
        sysUserLoginMapper.deleteById(id);
        return result;
    }

    /**
     * 根据用户名强制下线
     *
     * @param username 用户登录表用户名
     * @return 返回
     */
    @Override
    public Result forceOfflineByUsername(String username) {
        Result result = ResultTool.success();
        Transaction trans = null;
        try {
            //根据用户名查询用户登录信息
            QueryWrapper<SysUserLogin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", username);
            queryWrapper.eq("is_deleted", "0");
            List<SysUserLogin> sysUserLogin = sysUserLoginMapper.selectList(queryWrapper);
            List<String> ids = new ArrayList<>();
            if (!sysUserLogin.isEmpty()) {
                for (SysUserLogin userLogin : sysUserLogin) {
                    String Token = "LoginUsers:" + userLogin.getToken();
                    ids.add(userLogin.getId());
                    if(redisUtils.hasKey(Token)){
                        redisUtils.del(Token);
                    }
                }
            }
            trans = TransUtils.getTrans();
            trans.begin();
            sysUserLoginMapper.deleteBatchIds(ids);
            trans.commit();
        } catch (Exception e) {
            if (null != trans) {
                trans.rollback();
            }
            result = ResultTool.fail();
            result.setErrorMsg(e.getMessage());
            return result;
        }
        return result;
    }
}
